using dotnet_ef_admin.Src.Models;
using Microsoft.EntityFrameworkCore;

namespace dotnet_ef_admin.Src;

public class DbCtx(DbContextOptions<DbCtx> options) : DbContext(options) {
    // public DbCtx(DbContextOptions<DbCtx> options) : base(options) {
    // }

    public DbSet<Dept> Depts { get; set; }
    public DbSet<Dict> Dicts { get; set; }
    public DbSet<DictType> DictTypes { get; set; }
    public DbSet<Menu> Menus { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<UsersOnRoles> UsersOnRoles { get; set; }
    public DbSet<RolesOnMenus> RolesOnMenus { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<UsersOnRoles>()
            .HasKey(ur => new { ur.UserId, ur.RoleId });

        modelBuilder.Entity<UsersOnRoles>()
            .HasOne(ur => ur.User)
            .WithMany(u => u.Roles)
            .HasForeignKey(ur => ur.UserId)
            .OnDelete(DeleteBehavior.Cascade); // 设置级联删除


        modelBuilder.Entity<UsersOnRoles>()
            .HasOne(ur => ur.Role)
            .WithMany(r => r.Users)
            .HasForeignKey(ur => ur.RoleId)
            .OnDelete(DeleteBehavior.Cascade); // 设置级联删除


        modelBuilder.Entity<RolesOnMenus>()
            .HasKey(rm => new { rm.RoleId, rm.MenuId });

        modelBuilder.Entity<RolesOnMenus>()
            .HasOne(rm => rm.Role)
            .WithMany(r => r.Menus)
            .HasForeignKey(rm => rm.RoleId)
            .OnDelete(DeleteBehavior.Cascade); // 设置级联删除


        modelBuilder.Entity<RolesOnMenus>()
            .HasOne(rm => rm.Menu)
            .WithMany(m => m.Roles)
            .HasForeignKey(rm => rm.MenuId)
            .OnDelete(DeleteBehavior.Cascade); // 设置级联删除


        modelBuilder.Entity<Dict>()
            .HasOne(d => d.DictType)
            .WithMany(dt => dt.Dicts)
            .HasForeignKey(d => d.DictTypeId)
            .OnDelete(DeleteBehavior.Cascade); // 设置级联删除
    }
}